import type { MenuItem } from '@/components/Menu/types'

/**
 * 后端菜单数据结构
 */
export interface BackendMenuItem {
  id?: string | number
  menuId?: string | number
  name?: string
  title?: string
  menuName?: string
  icon?: string
  menuIcon?: string
  path?: string
  menuRoute?: string
  routePath?: string
  url?: string
  disabled?: boolean
  hidden?: boolean
  children?: BackendMenuItem[]
  [key: string]: any
}

/**
 * 将后端菜单数据转换为前端菜单组件需要的格式
 * @param backendMenus 后端返回的菜单数据
 * @returns 转换后的菜单数据
 */
export const transformBackendMenuToFrontend = (backendMenus: BackendMenuItem[]): MenuItem[] => {
  if (!Array.isArray(backendMenus)) {
    console.warn('菜单数据转换：输入数据不是数组')
    return []
  }

  return backendMenus
    .filter((menu) => menu && !menu.hidden) // 过滤掉隐藏的菜单
    .map((menu) => {
      const frontendMenu: MenuItem = {
        id: menu.id || menu.menuId || '',
        title: menu.title || menu.name || menu.menuName || '',
        icon: menu.icon || menu.menuIcon || '',
        path: menu.path || menu.menuRoute || menu.routePath || '',
        url: menu.url || '',
        disabled: menu.disabled || false,
        hidden: menu.hidden || false
      }

      // 递归处理子菜单
      if (menu.children && Array.isArray(menu.children) && menu.children.length > 0) {
        frontendMenu.children = transformBackendMenuToFrontend(menu.children)
      }

      return frontendMenu
    })
    .filter((menu) => {
      // 过滤掉没有标题的菜单项
      if (!menu.title || menu.title.trim() === '') {
        console.warn('菜单数据转换：发现没有标题的菜单项，已过滤:', menu)
        return false
      }
      return true
    })
}

/**
 * 验证菜单数据的有效性
 * @param menus 菜单数据
 * @returns 是否有效
 */
export const validateMenuData = (menus: MenuItem[]): boolean => {
  if (!Array.isArray(menus)) {
    return false
  }

  for (const menu of menus) {
    if (!menu || typeof menu !== 'object') {
      return false
    }

    if (!menu.id || !menu.title) {
      return false
    }

    if (menu.children && Array.isArray(menu.children)) {
      if (!validateMenuData(menu.children)) {
        return false
      }
    }
  }

  return true
}
